package routefinder.module;

import java.util.ArrayList;
import java.util.Hashtable;

public class RouteStoreSeaIaw extends RouteStore {
	ArrayList<String> locationList;
	Hashtable<String, Double> path;
	double shortestDistance;

	public RouteStoreSeaIaw() {
		locationList = new ArrayList<String>();
		path = new Hashtable<String, Double>();
	}

	public boolean addLocation(String locationName) {
		if (!locationList.contains(locationName)) {
			locationList.add(locationName);
			return true;
		}
		return false;
	}

	public boolean addPath(String fromLocation, String toLocation,
			double distance) {
		if (locationList.contains(fromLocation)
				&& locationList.contains(toLocation)) {
			path.put(fromLocation + " " + toLocation, distance);
			return true;
		}
		return false;
	}

	private double getShortestDistance(String fromLocation, String toLocation,
			double distance) {
		for (int i = 0; i < locationList.size(); i++) {
			if (!fromLocation.equalsIgnoreCase(locationList.get(i))) {
				double temp = this.computeDirectPath(fromLocation, locationList
						.get(i));
				if (temp != -1) distance += temp;
				if (locationList.get(i).equalsIgnoreCase(toLocation) && temp !=-1)
				{
					if (shortestDistance > distance)
						shortestDistance = distance;
				} else {
					if (temp == -1)
						continue;
					this.getShortestDistance(locationList.get(i),
							toLocation, distance);
					distance = 0;
				}
			}
		}
		return (shortestDistance == Double.MAX_VALUE) ? -1
				: shortestDistance;
	}

	public double getShortestDistance(String fromLocation, String toLocation) {
		shortestDistance = Double.MAX_VALUE;
		double distance = this.getShortestDistance(fromLocation, toLocation, 0);
		if (distance == -1)
			distance = this.getShortestDistance(toLocation, fromLocation, 0);
		return distance;
	}

	private double computeDirectPath(String fromLocation, String toLocation) {

		if (path.get(fromLocation + " " + toLocation) != null)
			return path.get(fromLocation + " " + toLocation);
		else
			return -1;
	}
}
